// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef CLOUDAPPENGINE_CAEHTTPSJOB_H
#define CLOUDAPPENGINE_CAEHTTPSJOB_H

#include <string>
#include "CaeSocketAgent.h"
#include "cJSON.h"
#include "../cae_common/CaeHttps.h"

enum HttpsJobType {
    NOTIFY_START,
    NOTIFY_STOP,
    NOTIFY_HEARTBEAT,
    QUERY_AES_KEY,
    QUERY_PUBLIC_CRT,
    JOB_TYPE_MAX,
};

class CaeHttpsJob {
public:
    ~CaeHttpsJob();

    static CaeHttpsJob &GetInstance();
    CaeHttpsJob(const CaeHttpsJob &) = delete;
    CaeHttpsJob &operator = (const CaeHttpsJob &) = delete;

    bool QueryAESKey(std::shared_ptr<CaeParamStorage> paramStorage);

    bool QueryPublicCrt(std::shared_ptr<CaeParamStorage> paramStorage);

    bool StartNotify(std::shared_ptr<CaeParamStorage> paramStorage);

    bool StopNotify(std::shared_ptr<CaeParamStorage> paramStorage);

    bool HeartbeatNotify(std::shared_ptr<CaeParamStorage> paramStorage);

    void SetPhoneId();

    bool ContainResponse(HttpsJobType type);

    HttpsResponse &GetResponse(HttpsJobType type);

    bool Init();

    void Deinit() noexcept;

    bool IsInit() const;

    void InitResponseMem(HttpsJobType httpsType);

    bool ParseHttpsResponse(HttpsResponse &responseInfo, HttpsJobType httpsType);

protected:
    CaeHttpsJob();

private:
    std::string m_phoneId;
    std::map<HttpsJobType, HttpsResponse> m_responseManager;
    void AddResponse(HttpsJobType type, HttpsResponse &response);
    pthread_mutex_t m_mutexInit;
    bool m_isInit;
    string GetPhoneId();
};

#endif // CLOUDAPPENGINE_CAEHTTPSJOB_H
